package com.example.app.util

import android.text.TextUtils
import com.example.app.data.bean.UserInfo
import com.google.gson.Gson
import com.tencent.mmkv.MMKV

val MMKV_ID = "app"

object CacheUtil {
    /**
     * 获取保存的账户信息
     */
    fun getUser(): UserInfo? {
        val kv = MMKV.mmkvWithID(MMKV_ID)
        val userStr = kv.decodeString("user")
        return if (TextUtils.isEmpty(userStr)) {
            null
        } else {
            Gson().fromJson(
                userStr, UserInfo::class.java
            )
        }
    }
    /**
     * 设置账户信息
     */
    fun setUser(userResponse: UserInfo?) {
        val kv = MMKV.mmkvWithID(MMKV_ID)
        if (userResponse == null) {
            kv.encode(
                "user", ""
            )
        } else {
            kv.encode(
                "user", Gson().toJson(userResponse)
            )
        }
    }
    /**
     * 是否已经登录
     */
    fun isLogin(): Boolean {
        var user = getUser()
        if (user != null) {
            return true
        } else {
            return false
        }
    }
    //获取token , 需要登录完后才有 , 用_id做token
    fun getToken(): String {
        return if (getUser() != null) {
            getUser()!!._id
        } else {
            ""
        }
    }

    fun getUserId(): String {

        var id = ""


        return if (getUser() != null) {
            getUser()!!._id
        } else {
            ""
        }
    }
}